package cn.kwq.pcsystem.excel;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.kwq.pcsystem.dto.SquadExcelDTO;
import cn.kwq.pcsystem.pojo.JSquadDic;
import cn.kwq.pcsystem.repository.SquadDicRepository;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: kwq
 * @Date: 2023/03/19/22:15
 * @Description:
 */
@Slf4j
public class SquadListener extends AnalysisEventListener<SquadExcelDTO> {
    /**
     * 每隔100条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    List<JSquadDic> list = new ArrayList<JSquadDic>();

    private SquadDicRepository squadDicRepository;

    public SquadListener(SquadDicRepository squadDicRepository) {
        this.squadDicRepository = squadDicRepository;
    }

    @Override
    public void invoke(SquadExcelDTO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", data);
        JSquadDic jSquadDic = BeanUtil.copyProperties(data, JSquadDic.class);
        jSquadDic.setDeleted(0);
        list.add(jSquadDic);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //未保存的保存进去
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        squadDicRepository.saveAll(list);
        log.info("存储数据库成功！");
    }
}
